package com.zhiyou.shiro;

import com.sun.javaws.IconUtil;
import com.zhiyou.bean.User;


import com.zhiyou.dao.RoleMapper;
import com.zhiyou.dao.UserMapper;

import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;

import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import tk.mybatis.mapper.entity.Example;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

public class ShiroRealm extends AuthorizingRealm {

    @Autowired
    UserMapper userMapper;

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        //认证
        System.out.println("=================认证=======================");
        UsernamePasswordToken token= (UsernamePasswordToken) authenticationToken;
        String username = token.getUsername();


        Example example = new Example(User.class);

        Example.Criteria criteria = example.createCriteria();

        //根据用户名DB查询对应的用户信息
        criteria.andEqualTo("uUsername",username);
        List<User> users = userMapper.selectByExample(example);
        SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(users.get(0),users.get(0).getuPassword(),getName());

        return info;
    }

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("==========================授权====================");
        User user = (User) principalCollection.getPrimaryPrincipal();
        //查询数据库 查出来当前用户的所有角色
        Set<String> roleNameSet =  userMapper.selectRolenameByUsername(user.getuUsername());


        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        info.addRoles(roleNameSet);
//        //通过用户名查询 当前用户在 数据库中所有的权限名称
        Set<String> permissinoSet = userMapper.selectPermissionByName(user.getuUsername());
        Set<String> permissions = new HashSet<>();
        for (String name:permissinoSet) {
           String[] names= name.split(",");
            for (String permission:names) {
                permissions.add(permission);
            }
        }
        //授权
        permissions.stream().forEach(s -> {
            System.out.println(s);
        });
        info.addStringPermissions(permissions);
//        permissionSet.stream().forEach(s->{
//            System.out.println(s);
//        });
//        System.out.println(user);
        return info;
    }
}
